package com.yubest.security.service.impl;

import com.yubest.security.bean.UserInfo;
import com.yubest.security.consts.Consts;
import com.yubest.security.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    private Map<String, UserInfo> userCacheMap = new HashMap<>();

    /**
     * 模拟数据
     */
    @PostConstruct
    public void init() {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(1L);
        userInfo.setUsername("admin");
        userInfo.setPassword(passwordEncoder.encode("123456"));
        //
        userInfo.setPermitCodeList(Arrays.asList(Consts.PERMIT_ALL));
        userCacheMap.put(userInfo.getUsername(), userInfo);

        UserInfo userInfo2 = new UserInfo();
        userInfo2.setId(1L);
        userInfo2.setUsername("test");
        userInfo2.setPassword(passwordEncoder.encode("123456"));
        userInfo2.setPermitCodeList(Arrays.asList("testx", "test2", "info"));
        userCacheMap.put(userInfo2.getUsername(), userInfo2);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userCacheMap.get(username);
        if (null == userInfo) {
            throw new BusinessException("用户不存在");
        }
        return userInfo;
    }
}
